<template>
  <div class="fdsMaterialDischargeRuleset-page">
    <div class="search-field">
      <el-form :model="searchForm" inline>
        <el-form-item label="编码" prop="number">
          <el-input
            placeholder="请输入排料规则编码"
            v-model="searchForm.number"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input
            placeholder="请输入排料规则名称"
            v-model="searchForm.name"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item>
          <div>
            <el-button type="primary" @click="startSearch"> 查询 </el-button>
            <el-button @click="startClear"> 重置 </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-pagination-content">
      <div class="btns-fun-field">
        <!-- v-if="userPermission.addUserPerm" -->
        <el-button
          type="primary"
          @click.prevent="showAddEditDialog"
          :icon="Plus"
        >
          新增排料规则
        </el-button>
        <el-button
          type="primary"
          @click.prevent="showRulesetScopeDialog"
          :icon="Plus"
        >
          设置排料规则应用范围
        </el-button>
      </div>
      <div class="table-field">
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          v-loading="tableLoading"
        >
          <el-table-column prop="number" label="编码" width="140" />
          <el-table-column prop="name" label="规则名称" width="140" />
          <el-table-column prop="content" label="规则内容" width="180" />
          <el-table-column
            prop="materialCount"
            label="排料物料数量"
            width="140"
          >
            <template #default="scope">
              <div class="table-column-item">
                <span>{{ scope.row.materialCount || 0 }}</span>
                <el-button
                  size="small"
                  style="margin-left: 12px"
                  type="primary"
                  @click="showMaterialCountDialog(scope.row)"
                  >查看物料</el-button
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="enabled" label="状态" width="80">
            <template #default="scope">
              <div
                class="table-column-item"
                style="display: flex; align-items: center"
              >
                <el-tag type="success" v-if="scope.row.enabled">启用</el-tag>
                <el-tag type="danger" v-else>禁用</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="170" />
          <el-table-column label="操作" min-width="220px" fixed="right">
            <template #default="scope">
              <!-- v-if="rolePermission.editRolePerm" -->
              <el-button
                type="success"
                size="small"
                @click.prevent="showAddEditDialog(scope.row, 2)"
                >编辑</el-button
              >
              <el-button
                v-if="scope.row.enabled"
                type="danger"
                size="small"
                @click.prevent="showEnabledDialog(scope.row, 2)"
                >禁用</el-button
              >
              <el-button
                v-else
                type="success"
                size="small"
                @click.prevent="showEnabledDialog(scope.row, 2)"
                >启用</el-button
              >
              <!-- v-if="rolePermission.removeRolePerm" -->
              <el-button
                type="danger"
                size="small"
                @click.prevent="showRemoveDialog(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-field">
        <el-pagination
          v-model:current-page="formData.pageIndex"
          v-model:page-size="formData.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="formData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <FdsMaterialDischargeRulesetAdd
      v-model="addUpdateRef"
    ></FdsMaterialDischargeRulesetAdd>
    <FdsMaterialDischargeRulesetRemove
      v-model="removeRef"
    ></FdsMaterialDischargeRulesetRemove>
    <LooKUserdMaterialList
      v-model="lookUserdMaterialListRef"
    ></LooKUserdMaterialList>
    <DischargeRulesetScope v-model="rulesetScopeRef"> </DischargeRulesetScope>
    <FdsMaterialDischargeRulesetEnable
      v-model="enabledRef"
    ></FdsMaterialDischargeRulesetEnable>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import {
  getFdsMaterialDischargeRulesetPagination,
  getFdsMaterialDischargeRulesetAllList,
} from '@/api/fds-material-discharge-ruleset.api'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
// import { useUserPermission } from "@/utils/permission.utils";
import FdsMaterialDischargeRulesetRemove from './FdsMaterialDischargeRulesetRemove.vue'
import FdsMaterialDischargeRulesetAdd from './FdsMaterialDischargeRulesetAdd.vue'
import DischargeRulesetScope from './DischargeRulesetScope.vue'
import LooKUserdMaterialList from './LookUsedMaterialList.vue'
import FdsMaterialDischargeRulesetEnable from './FdsMaterialDischargeRulesetEnable.vue'

import { getCanUseCode } from '@/api/fms-code-dict.api'

const titleName = `排料规则`
// const userPermission = useUserPermission();

const enabledRef = reactive({
  visible: false,
  form: {
    id: '',
    enabled: '',
  },
  refreshDataList: () => {
    getDataList()
  },
})
const showEnabledDialog = (item: any) => {
  enabledRef.visible = true
  enabledRef.form.id = item.id
  enabledRef.form.enabled = item.enabled ? '0' : '1'
}

/****
 * =============== 新增、修改相关操作 =====================
 */
const addUpdateRef = reactive({
  visible: false,
  disabled: false,
  title: `排料规则`,
  curSelectRow: {},
  roleList: [],
  form: {},
  rules: {
    number: [{ required: true, message: '请输入规则编码', trigger: 'blur' }],
    name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
  },
  refreshDataList: () => {
    getDataList()
  },
})

const lookUserdMaterialListRef = reactive({
  visible: false,
  title: `查看已使用该预警规则的物料列表`,
  curSelectRow: {},
  form: {},
  refreshDataList: () => {
    getDataList()
  },
})
const showMaterialCountDialog = (item) => {
  lookUserdMaterialListRef.visible = true
  lookUserdMaterialListRef.curSelectRow = item
  lookUserdMaterialListRef.form.id = item.id
}

// const requestCanUseCode = () => {
// 	getCanUseCode({ type: 8 })
// 			.then((res: any) => {
// 				console.log('getCanUseCode: ', res)
// 				addUpdateRef.form.number = res
// 			})
// 			.catch((err) => {
// 				ElMessage.error(err.msg)
// 			})
// }

const showAddEditDialog = (item: any, type: number) => {
  //新增
  if (item.target) {
    let form = {
      id: null,
      number: '',
      name: '',
      settingType: '1',
      selectedOption: 0,
      options: [
        {
          //小时
          hours: 1,
          value: 1,
          unit: 'g',
        },
        {
          hours: 1,
          value: 1,
          unit: 's',
        },
        {
          hours: 1,
          value: 1,
          unit: 'ml',
          extralValue: 1,
          extralUnit: 's',
        },
      ],
      dischargeSelectedOption: 0,
      dischargeOption: [
        {
          hours: 1,
          value: 1,
          unit: 's',
        },
      ],

      remark: '',

      enabled: '',
      intervalTime: '',
      materialCount: '',
      cleanTime: '',
      secondAmount: '',
      ruleType: '',
      configMap: '',
      disabled: false,
    }
    addUpdateRef.visible = true
    addUpdateRef.disabled = false
    addUpdateRef.form = form
    // requestCanUseCode()
    return
  }

  let form = {
    id: item.id,
    number: item.number,
    name: item.name,
    enabled: item.enabled,
    intervalTime: item.intervalTime,
    materialCount: item.materialCount,
    cleanTime: item.cleanTime,
    secondAmount: item.secondAmount,
    ruleType: item.ruleType,
    configMap: item.configMap,
    disabled: false,
  }
  addUpdateRef.visible = true
  addUpdateRef.disabled = true
  addUpdateRef.form = form
}

const rulesetScopeRef = reactive({
  visible: false,
  title: `排料规则`,
  curSelectRow: {},
  form: {
    id: '',
  },
  refreshDataList: () => {
    getDataList()
  },
})
const showRulesetScopeDialog = (item: any) => {
  rulesetScopeRef.visible = true
  rulesetScopeRef.curSelectRow = item
  rulesetScopeRef.form.id = item.id
}

/****
 * =============== 删除操作 =====================
 */
const removeRef = reactive({
  visible: false,
  title: `排料规则`,
  curSelectRow: {},
  refreshDataList: () => {
    getDataList()
  },
})
const showRemoveDialog = (item: any) => {
  removeRef.visible = true
  removeRef.curSelectRow = item
}

/****
 * =============== 搜索、表格、分页 =====================
 */
const formData = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

const searchForm = ref({
  number: '',
  name: '',
  enabled: '',
  intervalTime: '',
  materialCount: '',
  cleanTime: '',
  secondAmount: '',
  ruleType: '',
  configMap: '',
})

const tableLoading = ref(false)
const tableData = ref([])
/***
 * 开始搜索
 */
const startSearch = () => {
  formData.pageIndex = 1
  getDataList()
}

/***
 * 清空搜索条件
 */
const startClear = () => {
  formData.pageIndex = 1
  let value = searchForm.value
  Object.keys(value).forEach((key) => {
    ;(value as any)[key] = ''
  })
  getDataList()
}

const handleSizeChange = (value: number) => {
  formData.pageSize = value
  getDataList()
}

const handleCurrentChange = (value: number) => {
  formData.pageIndex = value
  getDataList()
}

const getDataList = () => {
  let searchCondition: any = {}

  let number = searchForm.value.number
  if (number) {
    searchCondition.number = number
  }
  let name = searchForm.value.name
  if (name) {
    searchCondition.name = name
  }
  let enabled = searchForm.value.enabled
  if (enabled) {
    searchCondition.enabled = enabled
  }
  let intervalTime = searchForm.value.intervalTime
  if (intervalTime) {
    searchCondition.intervalTime = intervalTime
  }
  let materialCount = searchForm.value.materialCount
  if (materialCount) {
    searchCondition.materialCount = materialCount
  }
  let cleanTime = searchForm.value.cleanTime
  if (cleanTime) {
    searchCondition.cleanTime = cleanTime
  }
  let secondAmount = searchForm.value.secondAmount
  if (secondAmount) {
    searchCondition.secondAmount = secondAmount
  }
  let ruleType = searchForm.value.ruleType
  if (ruleType) {
    searchCondition.ruleType = ruleType
  }
  let configMap = searchForm.value.configMap
  if (configMap) {
    searchCondition.configMap = configMap
  }

  tableLoading.value = true
  getFdsMaterialDischargeRulesetPagination({
    pageSize: formData.pageSize,
    pageIndex: formData.pageIndex,
    ...searchCondition,
  })
    .then(function (res: any) {
      tableLoading.value = false
      console.log(res)

      let list = res.list || []
      list = list.map((item: any) => {
        let content = ''

        if (item.settingType == 1 && item.selectedOption == 0) {
          content = `物料在${item.hours}小时内未出料，丢弃${item.value}gs物料`
        }
        if (item.settingType == 1 && item.selectedOption == 1) {
          content = `物料在${item.hours}小时内未出料，连续排除${item.value}s物料`
        }
        if (item.settingType == 1 && item.selectedOption == 2) {
          content = `物料在${item.hours}小时内未出料，需冲洗管路，冲水量${item.value}ml,冲洗完毕后填充管路${item.extralValue}秒物料`
        } else if (item.settingType != 1) {
        }
        item.content = content
        return item
      })
      tableData.value = list
      formData.total = Number(res.total)
    })
    .catch((error) => {
      console.log(error)
      tableLoading.value = false
    })
}

onMounted(() => {
  getDataList()
})
</script>
<style lang="scss" scoped>
.fdsMaterialDischargeRuleset-page {
  height: 100%;
}

.btns-fun-field {
  margin-bottom: 20px;
}

.pagination-field {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}

.btn-inner {
  display: flex;
  justify-content: center;
  color: #fff;
}

.tag-field {
  .el-tag {
    margin-right: 5px;
    &:last-child {
      margin-right: 0;
    }
  }
}

.search-field {
  margin-bottom: 12px;
  background: #fff;
  padding: 20px 20px 0px 20px;
  border-radius: 8px;
}

.fdsMaterialDischargeRuleset-page-content {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}
</style>
